package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.DishFlavor;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CacheManager cacheManager;

    /**
     * 分类分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> getPage(Integer page,Integer pageSize,String name){
        log.info("当前页数："+page+"数据"+pageSize);
        //构建分页构造器
        Page<Setmeal> pageIn = new Page(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
        //构建条件构造器
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        //根据名字进行模糊查询
        wrapper.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        //排序条件
        wrapper.orderByDesc(Setmeal::getUpdateTime);
        //执行查询
        setmealService.page(pageIn,wrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageIn,dtoPage,"records");
        List<Setmeal> records = pageIn.getRecords();
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item, setmealDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String name1 = category.getName();
                setmealDto.setCategoryName(name1);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 添加套餐
     * @param setmealDto
     * @return
     */
    @CacheEvict(value="setmealCache",allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("添加新员工");
//        setmealService.save(setmeal);
        setmealService.saveWithDish(setmealDto);
        return R.success("添加成功");
    }

    /**
     * 根据套餐id查询套餐数据
     * @param id
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#id",unless = "#result == null")
    @GetMapping("/{id}")
    public R<SetmealDto> getId(@PathVariable Long id){
        log.info("套餐:{}"+id);
        SetmealDto getid = setmealService.getid(id);
        return R.success(getid);
    }

    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
//    @CacheEvict(value = "setmealCache",key = "#result.id")
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        log.info("修改当前id内容");
//        setmealService.updateById(setmeal);
        setmealService.updateWithDish(setmealDto);
        return R.success("修改成功");
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)//清除所有缓存数据
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("删除所选id");
//        setmealService.removeById(id);
        setmealService.deleteWithDish(ids);
        return R.success("删除成功");
    }

    /**
     * 起售、禁售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> sell(@PathVariable("status") Integer status,@RequestParam List<Long> ids){
        log.info("当前状态为：{}"+status);
        setmealService.sellWithDish(status,ids);
        return R.success("状态修改成功");
    }

    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    @GetMapping("/list")
    public R<List<SetmealDto>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        wrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,1);
        wrapper.orderByAsc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(wrapper);
        List<SetmealDto> setmealDtoList = list.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            Long SetmealId = item.getId();
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getSetmealId,SetmealId);
            List<SetmealDish> dishFlavorList = setmealDishService.list(queryWrapper);
            setmealDto.setSetmealDishes(dishFlavorList);
            return setmealDto;
        }).collect(Collectors.toList());
        return R.success(setmealDtoList);
    }
}
